<template>
  <div style="width: 95%;margin: 10px 50px">
    <div style="margin-bottom: 50px;text-align: center;"><h2>toB测试账号</h2></div>

    <span style='display:block;float: left;margin-left: 30px'>
      <el-form :inline="true" :model="flag_select" class="demo-form-inline">
      <el-form-item>
        <el-select v-model="flag_select.use" placeholder="选择是否被使用">
          <el-option label="已使用" value="yes"></el-option>
          <el-option label="未使用" value="no"></el-option>
          <el-option label="全部" value="all"></el-option>
        </el-select>
        <el-select v-model="flag_select.proj" placeholder="选择项目名称">
          <el-option label="全部" value="all"></el-option>
          <el-option
            v-for="(item, index) in project_option"
            :key="index"
            :value="item"
            :label="item">
          </el-option>
        </el-select>
        <el-select v-model="flag_select.port" placeholder="选择组合类型">
          <el-option label="全部" value="all"></el-option>
          <el-option label="保守型" value="保守型"></el-option>
          <el-option label="稳健型" value="稳健型"></el-option>
          <el-option label="平衡型" value="平衡型"></el-option>
          <el-option label="成长型" value="成长型"></el-option>
          <el-option label="进取型" value="进取型"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit_search">查询</el-button>
      </el-form-item>
    </el-form>
    </span>
    <span style='display:block;float: right;margin-right: 50px'>
      <el-button type="primary" icon="el-icon-download" @click="func_download()">账号下载</el-button>
    </span>

    <span style="position: relative; left: 20px;">
      <el-button type="primary" icon="el-icon-plus" @click="showAddDialog"> {{ addTitle }} </el-button>
      <AccountModal ref="addAccountModal"
                    :operate="addOperate"
                    :title="addTitle"
                    @listAccount="listAccount">
      </AccountModal>
    </span>

<!--    <DataBatchOperate :batch="edit_batch_status" :down_uids="download" @batch_events="func_get_batch_status" @batch_set="batch_flag_set"></DataBatchOperate>-->

    <el-table
      ref="acc_table"
      @selection-change="handle_selection_change"
      :data="tableData"
      :default-sort = "{prop: ['create_time'], order: 'descending'}"
      height="700px"
      border
      style="width: 100%;"
      :row-key="get_row_key">
      <el-table-column
        :reserve-selection="true"
        type="selection"
        width="50">
      </el-table-column>
      <el-table-column
        fixed
        prop="project"
        label="项目"
        width="120px">
      </el-table-column>
      <el-table-column
        fixed
        prop="env"
        label="环境"
        width="100px">
      </el-table-column>
      <el-table-column
        fixed
        prop="userName"
        label="用户名"
        width="100px">
      </el-table-column>
      <el-table-column
        fixed
        prop="phone"
        label="电话"
        width="120px">
      </el-table-column>
      <el-table-column
        fixed
        prop="email"
        label="邮箱"
        width="150px">
      </el-table-column>
      <el-table-column
        fixed
        prop="clientId"
        label="客户号"
        width="120px">
      </el-table-column>
      <el-table-column
        fixed
        prop="flagUsage"
        label="是否使用"
        width="100px">
      </el-table-column>
      <el-table-column
        fixed
        prop="isHold"
        label="是否持仓"
        width="100px">
      </el-table-column>
      <el-table-column
        prop="loginPassword"
        label="登录密码"
        width="100px">
      </el-table-column>
      <el-table-column
        prop="transPassword"
        label="交易密码"
        width="100px">
      </el-table-column>
      <el-table-column
        prop="verifyCode"
        label="验证码"
        width="100px">
      </el-table-column>
      <el-table-column
        prop="raasUid"
        label="UID"
        width="100px">
      </el-table-column>
      <el-table-column
        prop="accountId"
        label="Account ID"
        width="100px">
      </el-table-column>
      <el-table-column
        prop="portfolioId"
        label="PortfolioID"
        width="100px">
      </el-table-column>
      <el-table-column
        prop="userRiskType"
        label="用户风险类型"
        width="200px">
      </el-table-column>
      <el-table-column
        prop="holdings"
        label="持仓组合"
        width="100px">
      </el-table-column>
      <el-table-column
        prop="hasAdvice"
        label="是否可调仓"
        width="100px">
      </el-table-column>
      <el-table-column
        label="账号操作记录"
        width="400px">
        <template v-slot="scope">
          <el-input
            readonly
            type="textarea"
            :rows="5"
            placeholder="请输入内容"
            :value="scope.row.operateRecord">
          </el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        width="100px">
      </el-table-column>
      <el-table-column
        sortable
        prop="gmtCreated"
        label="创建时间"
        width="180px">
      </el-table-column>
      <el-table-column
        sortable
        prop="gmtModified"
        label="更新时间"
        width="180px">
      </el-table-column>
      <el-table-column
        prop="operate"
        label="操作"
        width="500px">
        <template slot-scope="scope">
          <el-tooltip class="tooltip" effect="dark" :content=editTitle placement="top">
              <el-button type="primary" icon="el-icon-edit" circle @click="showEditDialog(scope.$index, scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="danger" icon="el-icon-delete" circle @click="func_del_acc(scope.$index, scope.row, tableData)"></el-button>
          </el-tooltip>
        </template>
        <AccountModal ref="editAccountModal"
                      :operate="editOperate"
                      :title="editTitle"
                      :par-query.sync="queryParams"
                      :flag-select.sync="flag_select"
                      :page-num.sync="current_page"
                      @listAccount="listAccount">

        </AccountModal>
      </el-table-column>
    </el-table>

    <div style="margin-top: 10px;margin-right:30px;float:right">
      <el-pagination
        background
        @current-change="handle_current_change"
        :current-page="current_page"
        :total="total_numbers"
        :page-size="page_size"
        layout="prev, pager, next">
      </el-pagination>
    </div>
  </div>
</template>

<script>

import DataBatchOperate from "@/components/data/DataBatchOperate";
import AccountModal from "@/components/data/AccountModal";
import {
  raas_delete_acc,
  raas_export_account,
  raas_get_all_accs,
} from '@/api/account'

export default {
  name: 'AqmData',
  components:{
    DataBatchOperate,
    AccountModal
  },
  data() {
    return {
      addTitle: '新增测试账号',
      addOperate: 'add',
      editTitle : '编辑测试账号',
      editOperate: 'edit',
      current_page: 1,  // 初始页
      page_size: 10,    // 每页展示的数据条数
      total_numbers: 1,
      single_uid: '',
      edit_single_status: false,
      flag_select: {
        use: '',
        proj: '',
        port: ''
      },
      queryParams: {},
      project_option: ['华泰2', '中信', '方德', '大唐中', 'pro', '华泰434'],
      tableData: []
    }
  },
  methods: {
    submit_search(){
      console.log('查询选择项：',this.flag_select)
      let params = {
        flagUsage: this.flag_select.use === "all" ? "" : this.flag_select.use,
        project: this.flag_select.proj === "all"? "": this.flag_select.proj,
        holdings: this.flag_select.port === "all"? "" : this.flag_select.port
      }
      this.queryParams = params
      this.listAccount(params)
    },
    func_download(){
      let select_row = this.$refs.acc_table.selection;
      let id_list = [];
      for (let i=0;i<select_row.length;i++){
        id_list.push(select_row[i].id);
      }
      console.log(id_list)
      let params = {
        ids: id_list.join(',')
      }
      raas_export_account(params).then((res) => {
        console.log('请求下载返回：', res)
        if (res.status === 200) {
          //获取文件名
          let fileName = decodeURIComponent(res.headers["content-disposition"].split(";")[1].split("=")[1])
          // let fileName = revertUTF8(res.headers["content-disposition"].split(";")[1].split("=")[1])
          const blob = new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8"})
          //创建一个a标签并设置href属性，之后模拟人为点击下载文件
          let link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName;//设置下载文件名
          link.click();//模拟点击
          //释放资源并删除创建的a标签
          window.URL.revokeObjectURL(link.href)
          link.remove();
          this.$message({
            type: 'success',
            message: '导出成功!'
          })
        }
      }).catch((err) =>{
        this.$message({
          type: 'error',
          message: err
        });
      })
    },
    handle_selection_change(val){
      console.log('选择的行数据val=', val)
    },
    get_row_key(row){
      return row.id
    },
    func_del_acc(index, row, td){
      console.log('delete')
      let params = {
        id: row.id
      }
      this.$confirm('此操作将删除该账号: UID = '+ row.raasUid +', 是否继续?' , '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        td.splice(index, 1)
        console.log('delete params=', params)
        raas_delete_acc(params).then((res) => {
          console.log('delete res=', res)
          if (res.code === 200 && res.data) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除！'
        });
      });
    },
    handle_current_change(val){
      this.current_page = val;
      let params = {
        pageNum: this.current_page
      }
      this.listAccount(params)
    },
    showAddDialog() {
      this.$refs.addAccountModal.showDialog()
    },
    showEditDialog: function (index, row) {
      console.log("编辑对话框: ", index)
      this.$refs.editAccountModal.showDialog(index, row)
    },
    listAccount(params) {
      raas_get_all_accs(params).then((res) => {
        this.tableData = res.data? res.data.dataSources.map(item => {
          if(item.flagUsage === 0) {
            item.flagUsage = '否'
          } else {
            item.flagUsage = '是'
          }
          if(item.isHold === 0) {
            item.isHold = '否'
          } else {
            item.isHold = '是'
          }
          if(item.hasAdvice === 0) {
            item.hasAdvice = '否'
          } else {
            item.hasAdvice = '是'
          }
          return item
        }) : [];
        this.total_numbers = res.data.total;
      }).catch((err) => {
        console.log('get_all_accs 异常结果：', err)
      })
      this.listAccProject()
    },
    listAccProject() {
      raas_get_all_accs().then((res) => {
        this.project_option = res.data? [...new Set(res.data.dataSources.map(item => item.project))]: []
      })
    }
  },
  created() {
    let params = {}
    this.$nextTick(() => {
      this.listAccount(params)
      // this.listAccProject()
    })
  }
}
</script>

<style scoped>
.tooltip {
  margin: 4px;
}
</style>
